package com.yc.bank.biz;

import com.yc.bank.dao.AccountDao;
import com.yc.bank.dao.OprecordDao;
import com.yc.bank.entity.Account;
import com.yc.bank.entity.Oprecord;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
@Transactional
public class AccountBiz {

    @Resource
    AccountDao adao;
    @Resource
    OprecordDao odao;

    // 存款
    @Transactional
    public void deposit(String id, double money) {
        adao.updateBalance(id, money);
        Oprecord oprecord = new Oprecord();
        oprecord.setAid(id);
       // int i = 1/0;
        oprecord.setOpmoney(money);
        odao.insert(oprecord);
    }

    // 取款
    public void withdraw(String id, double money) throws BizException {
        final Account account = adao.selectById(id);
        if(account.getBalance() < money){
            throw new BizException("账号余额不足");
        }
        adao.updateBalance(id, -money);
        Oprecord oprecord = new Oprecord();
        oprecord.setAid(id);
        oprecord.setOpmoney(-money);
        odao.insert(oprecord);
    }
    // 转账
    // noRollbackFor 不会回滚异常 => 类型:
    @Transactional(rollbackFor = {BizException.class} )
    public void transform(String id1, String id2, double money) throws BizException {
        deposit(id1, money);
        withdraw(id2, money);
    }

}
